<template>
    <div class="container">
        <div class='u-title f-mtp10'>
            <h2>{{h2_title}}</h2>
        </div>

        <div class='u-content mn flex flex-column flex-center'>
            <div class='item'>
                <label class='tip' for="">知识标题</label>
                <div class='item-right'>
                    <el-input v-model="title" placeholder="知识标题"></el-input>
                </div>
            </div>
            <div class='item'>
              <label class='tip' for="">封面图片</label>
              <div class='item-right'>
                <div class="u-upload">
                  <input
                    type="file"
                    @change="upCoverImg"
                    name="file"
                    id="file"
                    accept="image/png, image/jpeg, image/gif, image/jpg"
                    class="u-upload-file"
                  >
                  <label for="file" class="btn btn-success">
                    <img v-if="picUrl" :src="picUrl" alt="">
                    <i class='el-icon-plus' v-else></i>
                  </label>
                </div>
              </div>
            </div>
            <div class='item'>
                <label for="">摘要</label>
                <div class='item-right'>
                    <el-input type="textarea" row='4' v-model="remark" placeholder="摘要"></el-input>
                </div>
            </div>
            <div class='item'>
                <label class='tip' for="">所属分类</label>
                <div class='item-right'>
                  <CaseTypeSelect @getCaseType='getCaseType' ref="caseType" placeholder='所属分类' class='f-w-full' />
                </div>
            </div>
            <div class='item'>
                <label class='tip' for="">所属推荐</label>
                <div class='item-right'>
                  <el-select class='f-w-full' v-model="knowledgeType" clearable placeholder="所属推荐">
                    <el-option
                      clearable
                      v-for="item in knowledgeTypeList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </div>
            </div>
            <div class='item'>
                <label class='tip' for="">内容详情</label>
                <div class='item-right'>
                    <quill-editor v-model="content"
                        ref="myQuillEditor"
                        :options="editorOption"
                        @change="onEditorChange"
                        >
                    </quill-editor>
                    <input v-show='false' type="file" @change="upImg" id='upImg' ref="upImg" accept="image/png, image/jpeg, image/gif, image/jpg" />
                </div>
            </div>
            <div class='btn-box f-ptp20'>
                <el-button
                    class='f-w300 s-bg-green s-cfff'
                    @click="submit">提交</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import CaseTypeSelect from '../../components/CaseTypeSelect'
import config from '../../config'
export default {
  name: 'AddKnowledge',
  components: {
    'CaseTypeSelect': CaseTypeSelect
  },
  data() {
    return {
      h2_title: '新增知识',
      content: '',
      remark: '',
      picUrl: '',
      editorOption: { 
        theme: 'snow',
        placeholder: '请在此输入内容详情...',
        modules: {
          toolbar: {
            container: config.toolbarOptions,
            handlers: {
              'image': function(value) {
                if(value) {
                  document.querySelector('#upImg').click()
                } else {
                  this.quill.format('image', false);
                }
                
              }
            }
          }
        }
      }, // 富文本配置
      title: '',
      caseType: '',
      knowledgeTypeList: [],
      knowledgeType: '',
      id: null,
    }
  },
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill
    }
  },
  mounted() {
    console.log('this is current quill instance object', this.editor)
  },
  created: function() {
    this.getKnowledgeTypeList();
    if (this.$route.params.id) {
      this.id = this.$route.params.id;
      this.h2_title = "编辑知识";
      this.getKnowledgeById();
    }
  },
  methods: {
    // 上传封面图片
    upCoverImg(e) {
      this.upfile(e, 'cover')
    },
    // 富文本上传图片
    upImg(e) {
      this.upfile(e, 'editor')
    },
    // 上传图片
    upfile(e, type) {
      const files = e.target.files;
      const form = new FormData();
      form.append("file", files[0]);
      form.append("dir", "knowledge");
      form.append("type", "1");
   
      this.$store.dispatch("UPLOAD_FILE", form).then(res => {
        if(res.data.retCode == 0) {
          this.$message.success('上传成功！');
          if(type == 'cover') {
            this.picUrl = res.data.data;
          }
          if(type == 'editor') {
            // 获取富文本组件实例
            let quill = this.$refs.myQuillEditor.quill;
            // 获取光标所在位置
            let length = quill.getSelection().index;
            // 插入图片，res为服务器返回的图片链接地址
            quill.insertEmbed(length, 'image', res.data.data)
            // 调整光标到最后
            quill.setSelection(length + 1)
          }
        } else {
          res.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      });
    },
    // 获取知识分类
    getKnowledgeTypeList() {
      this.$store.dispatch('GET_KNOWLEDGE_tYPE_LIST').then(res => {
        if(res.data.retCode == 0) {
          this.knowledgeTypeList = res.data.data;
        } else {
          res.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      })
    },
    // 获取所属分类
    getCaseType(caseType) {
      this.caseType = caseType;
    },
    onEditorChange({ quill, html, text }) {
      console.log('editor change!', quill, html, text)
      this.content = html
    },  
    // 提交按钮点击事件
    submit() {
      if(this._utils.isEmpty(this.title)) {
        this.$message.warning('请输入标题！');
        return;
      }
      if(this._utils.isEmpty(this.picUrl)) {
        this.$message.warning('请上传封面图片！');
        return;
      }
      if(this._utils.isEmpty(this.caseType)) {
        this.$message.warning('请选择所属分类！');
        return;
      }
      if(this._utils.isEmpty(this.knowledgeType)) {
        this.$message.warning('请输入所属推荐！！');
        return;
      }
      if(this._utils.isEmpty(this.content)) {
        this.$message.warning('请输入内容详情！');
        return;
      }
      if(this.id) {
        this.updateKnowledge();
      } else {
        this.addKnowledge();
      }
    },
    
    // 法律知识-新增知识
    addKnowledge() {
      this.$store.dispatch('ADD_KNOWLEDGE', {
        title: this.title,
        caseType: this.caseType,
        knowledgeType: this.knowledgeType,
        content: this.content,
        remark: this.remark,
        picUrl: this.picUrl
      }).then(res => {
        if(res.data.retCode == 0) {
          this.$message.success('新增成功！');
          this.$router.push('/home/legalKnowledge');
        } else {
          res.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      })
    },

    // 获取知识详情
    getKnowledgeById() {
      this.$store.dispatch('GET_KNOWLEDGE_DETAIL', {
        id: this.id,
      }).then(res => {
        if(res.data.retCode == 0) {
          const knowledge = res.data.data;
          this.title = knowledge.title;
          this.caseType = knowledge.caseType;
          this.knowledgeType = knowledge.knowledgeType;
          this.picUrl = knowledge.picUrl;
          this.content = knowledge.content;
          this.remark = knowledge.remark;
          this.$refs.caseType.setValue(knowledge.caseType);
        } else {
          res.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      })
    },

    // 法律知识-更新知识
    updateKnowledge() {
      this.$store.dispatch('ADD_KNOWLEDGE', {
        id: this.id,
        title: this.title,
        caseType: this.caseType,
        picUrl: this.picUrl,
        remark: this.remark,
        knowledgeType: this.knowledgeType,
        content: this.content
      }).then(res => {
        if(res.data.retCode == 0) {
          this.$message.success('更新成功！');
          this.$router.push('/home/legalKnowledge');
        } else {
          res.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.upload-tip{
    font-size: 12px;
    color: #999;
    margin-top: 10px;
    line-height: 24px;
}

.container{
  width: 900px;
  /* margin: 0 auto; */
}
.mn{
    padding: 30px 0 50px 0;
}
.item{
    display: flex;
    margin-bottom: 10px;
}
.item>label{
    display: inline-block;
    width: 90px;
    line-height: 40px;
    text-align: right;
    margin-right: 10px;
}
.item>.tip::before{
    content: '*';
    line-height: 40px;
    color: red;
    margin-right: 5px;
}
.item-right{
    width: 700px
}
.btn-box{
    padding-left: 90px;
}
</style>
